package xyz.yuzegod.megawalls.listener;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.block.ContainerBlock;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import xyz.yuzegod.megawalls.MegaWalls;
import xyz.yuzegod.megawalls.classes.Classes;
import xyz.yuzegod.megawalls.classes.ClassesManager;
import xyz.yuzegod.megawalls.game.ChestManager;
import xyz.yuzegod.megawalls.game.Game;
import xyz.yuzegod.megawalls.game.GamePlayer;
import xyz.yuzegod.megawalls.game.stage.ProtectStage;
import xyz.yuzegod.megawalls.util.ItemUtils;
import xyz.yuzegod.megawalls.util.PlayerUtils;

import java.util.Collection;

public class BlockListener extends BaseListener
{
    private final Game game;
    
    public BlockListener(final MegaWalls plugin) {
        super(plugin);
        this.game = plugin.getGame();
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onBlockBreak(final BlockBreakEvent e) {
        final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
        Collection<ItemStack> drops=e.getBlock().getDrops();
        if (gamePlayer.isSpectator() || !this.game.isStarted() || this.game.getStageManager().currentStage() instanceof ProtectStage) {
            e.setCancelled(true);
            return;
        }
        if (this.game.isProtected(e.getBlock().getLocation())) {
            e.setCancelled(true);
            gamePlayer.sendMessage("§c你不可以修改你的城堡！");
            return;
        }
        if (this.game.isUnbreakable(e.getBlock().getLocation())) {
            e.setCancelled(true);
            return;
        }
        final Block block = e.getBlock();
        if ((block.getType() != Material.FURNACE && block.getType() != Material.BURNING_FURNACE && block.getType() != Material.TRAPPED_CHEST) || this.game.isWallsFall()) {
            if (!this.game.isWallsFall()) {
                gamePlayer.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 100, 1));
            }
            final byte data = block.getData();
            if (block.getType() == Material.LOG && !this.game.isWallsFall()) {
                Bukkit.getScheduler().runTaskLater((Plugin)MegaWalls.getInstance(), (Runnable)new Runnable() {
                    @Override
                    public void run() {
                        if (block.getLocation().getBlock().getType() == Material.AIR) {
                            block.setType(Material.LOG);
                            block.setData(data);
                            block.getWorld().playSound(block.getLocation(), Sound.CHICKEN_EGG_POP, 1.0f, 1.0f);
                        }
                    }
                }, 400L);
            }
            if ((e.getBlock().getType() == Material.STONE || e.getBlock().getType() == Material.COBBLESTONE || e.getBlock().getType() == Material.COAL_ORE || e.getBlock().getType() == Material.IRON_ORE || e.getBlock().getType() == Material.GOLD_ORE || e.getBlock().getType() == Material.LOG || e.getBlock().getType() == Material.LOG_2) && MegaWalls.getRandom().nextInt(this.game.isWallsFall() ? 1000 : 150) <= 6) {
                e.setCancelled(true);
                block.setType(Material.TRAPPED_CHEST);
                gamePlayer.addProtectedBlock(block);
                final Chest chest = (Chest)block.getState();
                block.getWorld().spawn(block.getLocation(), Firework.class);
                ChestManager.fillInventory(e.getPlayer(), chest.getBlockInventory());

            }else if (!game.isWallsFall()){
                e.getBlock().setMetadata("type",new FixedMetadataValue(getPlugin(),e.getBlock().getType()));
                for (ItemStack is: drops){
                    if (ItemUtils.isFullInventory(gamePlayer.getPlayer().getInventory())){
                        if (ItemUtils.isFullInventory(gamePlayer.getEnderChest())){
                            break;
                        }else {

                            gamePlayer.getEnderChest().addItem(is);


                        }
                    }else {

                        gamePlayer.getPlayer().getInventory().addItem(is);

                    }
                }
                e.getBlock().getWorld().getBlockAt(e.getBlock().getLocation()).setType(Material.AIR);
            }
            final Classes classes = ClassesManager.getSelected(gamePlayer);
            classes.getCollectSkill().onBlockBreak(gamePlayer.getPlayerStats().getKitStats(classes), e);
            return;
        }
        if (!gamePlayer.isProtectedBlock(block)) {
            e.setCancelled(true);
            gamePlayer.sendMessage("§c你不能破坏受保护的方块！");
            return;
        }


        if (block.getType() == Material.FURNACE) {
            gamePlayer.sendMessage("§a你破坏了你保护的§e熔炉");
        }
        else if (block.getType() == Material.TRAPPED_CHEST) {
            gamePlayer.sendMessage("§a你破坏了你保护的§e陷阱箱");
        }
        if (block.getType() == Material.FURNACE || block.getType() == Material.BURNING_FURNACE || block.getType() == Material.TRAPPED_CHEST||block.getType()==Material.CHEST) {
            e.getBlock().setMetadata("type", new FixedMetadataValue(getPlugin(), e.getBlock().getType()));
            Inventory inventory= ((ContainerBlock) block.getState()).getInventory();
            e.setCancelled(true);


            for (ItemStack is: inventory.getContents()){
                if (is==null){
                    continue;
                }
                if (ItemUtils.isFullInventory(gamePlayer.getPlayer().getInventory())){
                    if (ItemUtils.isFullInventory(gamePlayer.getEnderChest())){
                        break;
                    }else {

                        gamePlayer.getEnderChest().addItem(is);


                    }
                }else {

                    gamePlayer.getPlayer().getInventory().addItem(is);

                }
            }
            PlayerUtils.gatheringItem(new ItemStack(e.getBlock().getType()),e);
            //e.getBlock().getWorld().getBlockAt(e.getBlock().getLocation()).setType(Material.AIR);
            ((ContainerBlock) block.getState()).getInventory().clear();

            e.getBlock().setType(Material.AIR);

        }
        gamePlayer.removeProtectedBlock(e.getBlock());
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onBlockPlace(final BlockPlaceEvent e) {
        final GamePlayer gamePlayer = GamePlayer.get(e.getPlayer().getUniqueId());
        if (gamePlayer.isSpectator() || !this.game.isStarted()) {
            e.setCancelled(true);
            return;
        }
        if (this.game.isProtected(e.getBlock().getLocation())) {
            e.setCancelled(true);
            e.setBuild(false);
            gamePlayer.sendMessage("§c你不可以修改你的城堡！");
            return;
        }
        if (this.game.isUnbreakable(e.getBlock().getLocation())) {
            e.setCancelled(true);
            e.setBuild(false);
            return;
        }
        final Block block = e.getBlock();
        if (!this.game.isWallsFall()) {
            for (final BlockFace face : BlockFace.values()) {
                final Block relativeBlock = block.getRelative(face);
                if (relativeBlock != null && !relativeBlock.equals(block) && (relativeBlock.getType() == Material.TRAPPED_CHEST || relativeBlock.getType() == Material.FURNACE)) {
                    e.setCancelled(true);
                    e.setBuild(false);
                    gamePlayer.sendMessage("§c你不能在受保护的方块附近一格内摆放其他方块！");
                    return;
                }
            }
            if (block.getType() == Material.FURNACE || block.getType() == Material.TRAPPED_CHEST) {
                gamePlayer.addProtectedBlock(block);
                if (block.getType() == Material.FURNACE) {
                    gamePlayer.sendMessage("§a你的§e熔炉§a已被保护！");
                }
            }
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onHangingBreakByEntity(final HangingBreakByEntityEvent e) {
        if (!(e.getRemover() instanceof Player)) {
            return;
        }
        if (GamePlayer.get(e.getRemover().getUniqueId()).isSpectator() || !this.game.isStarted()) {
            e.setCancelled(true);
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onHangingPlace(final HangingPlaceEvent e) {
        if (!(e.getEntity() instanceof Player)) {
            return;
        }
        if (GamePlayer.get(e.getPlayer().getUniqueId()).isSpectator() || !this.game.isStarted()) {
            e.setCancelled(true);
        }
    }
    
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onBlockIgnite(final BlockIgniteEvent e) {
        e.setCancelled(true);
    }
}
